<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { GoodsShelvesVo } from '@/types/goodsShelves'
import type { DonationType } from '@/types/home'
import { getListPickuptAPI } from '@/services/goodsShelves'
import DonationItem from './donation-item.vue'
import { putStorageOrPickUpAPI } from '@/services/donation'

// 定义组件属性
const props = defineProps<{
  type: string // pickup 或 storage，对应 API 参数中的 type: 0 或 1
  donationTypes: DonationType[]
}>()

// 定义事件
const emit = defineEmits(['pickup', 'openDoor'])

// 设备号
const deviceNumber = 'iSknMG7O'

// 捐赠物列表
const donationList = ref<GoodsShelvesVo[]>([])

// 加载状态
const loading = ref(false)
// 下拉刷新状态
const refreshing = ref(false)

const total = ref(0)
const finished = ref(false)

// 获取列表数据
const fetchData = async (refresh = false) => {
  try {
    if (refresh) {
      refreshing.value = true
    } else {
      loading.value = true
    }

    console.log(`正在获取${props.type}列表数据...`)
    // 根据 props.type 传递不同的 type 参数: pickup 对应 0, storage 对应 1
    const apiType = props.type === 'pickup' ? 0 : 1
    console.log(`请求参数: deviceNumber=${deviceNumber}, type=${apiType}`)
    // 确保只传递deviceNumber参数
    const res = await getListPickuptAPI({ deviceNumber }, apiType)
    console.log(`${props.type}列表数据响应:`, res)

    if (res.code === 200) {
      if (refresh) {
        donationList.value = res.rows
      } else {
        donationList.value = [...donationList.value, ...res.rows]
      }

      total.value = res.total || 0
      console.log(`获取到${props.type}列表数据，总数:`, donationList.value.length)
    }
  } catch (error) {
    console.error('获取列表数据失败:', error)
    uni.showToast({
      title: '获取列表数据失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 处理取货
const handlePickup = (item: GoodsShelvesVo) => {
  emit('pickup', item)
  uni.showModal({
    title: '取货',
    content: '确认取货吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await putStorageOrPickUpAPI(item, 'pickup')
        if (res.code === 200) {
          uni.showToast({
            title: '已取货',
            icon: 'success',
          })
          // 刷新数据
          refresh()
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'error',
          })
        }
      }
    },
  })
}

// 处理开门
const handleOpenDoor = (item: GoodsShelvesVo) => {
  emit('openDoor', item)
  uni.showModal({
    title: '开门',
    content: '确认开门入库吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await putStorageOrPickUpAPI(item, 'storage')
        if (res.code === 200) {
          uni.showToast({
            title: '已开门',
            icon: 'success',
          })
          // 刷新数据
          refresh()
        } else {
          uni.showToast({
            title: '开门失败',
            icon: 'error',
          })
        }
      }
    },
  })
}

// 刷新数据
const refresh = () => {
  console.log(`开始刷新${props.type}列表数据`)
  return fetchData(true)
}

// 下拉刷新回调
const onRefresh = () => {
  refresh()
}

// 加载更多
const loadMore = () => {
  if (finished.value) return
  fetchData()
}

// 定义对外暴露的方法
defineExpose({
  refresh,
  loadMore,
})

onMounted(() => {
  console.log(`donation-list组件(${props.type})已挂载，准备获取数据`)
  fetchData()
})
</script>

<template>
  <view class="donation-list">
    <!-- 使用scroll-view包裹整个列表内容，启用下拉刷新 -->
    <scroll-view
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      class="scroll-container"
    >
      <!-- 无数据提示 -->
      <view v-if="!loading && donationList.length === 0" class="empty-tip">
        <text>暂无数据</text>
      </view>

      <!-- 数据列表 -->
      <view v-else class="list-content">
        <donation-item
          v-for="item in donationList"
          :key="item.id"
          :item="item"
          :donation-types="donationTypes"
          :type="type"
          @pickup="handlePickup"
          @open-door="handleOpenDoor"
        />
      </view>

      <!-- 加载状态 -->
      <view class="loading-more" v-if="loading">
        <text>加载中...</text>
      </view>
      <view class="loading-more" v-else-if="finished && donationList.length > 0">
        <text>-- 已加载全部 --</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
.donation-list {
  padding: 20rpx;
  height: 100%;

  .scroll-container {
    height: calc(100vh - 200rpx);
  }

  .empty-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;
    color: #999;
    font-size: 28rpx;
  }

  .list-content {
    padding-bottom: 20rpx;
  }

  .loading-more {
    text-align: center;
    color: #999;
    font-size: 24rpx;
    padding: 20rpx 0;
  }
}
</style>
